# Simple AJAX chess website - Room related handlers
#
# Copyright (C) 2008  Hong Anh Khoa
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from basehandler import BaseRequestHandler
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users

from datamodel import *
from cgi import escape
import datetime

import time

import modules.utilities as utilities

class CreateRoomHandler(BaseRequestHandler):
  # Handler for creating room function.
  
  @login_required
  def get(self):
    # Generate the form for creating new room.
    form = self.generate('createroom.tpl.html', {'action': self.request.path})
    
    self.response.out.write(self.generate_page({'content': form}))
    
    
  def post(self):
    # Process when the form is submitted."""
    
    # Get the form values."""
    name = escape(self.request.get("name"))
    passw = self.request.get("pass")
    
    # Checking for errors."""
    if (name == ""):
      self.errors = ["Room name is required."]
      form = self.generate('createroom.tpl.html', {'action': self.request.path})
      self.response.out.write(self.generate_page({'content': form}))
      return
    
    # Create new room.
    room = Room(creator = users.get_current_user(),
                name = name,
                active = True,
                password = passw,
                users = 1)
    
    roomid = room.put()
    
    # Redirect to the new room.
    self.redirect('/room/%s' % roomid)



class RoomViewHandler(BaseRequestHandler):
  # Handler for in-room view
  
  def get(self, roomid):
    # Get the room from the datastore
    try:
      room = Room.get(roomid);
    except:
      self.error(404)
      return
      
    # Set the title.
    self.title =  self.get_title() + ' | Room: ' + room.name
    
    # Add javascripts
    self.js = ['chat.js', 'game.js']
    self.inline_js = ['var roomid="' + roomid + '";']
    
    ctime = int(time.time())
    self.inline_js += ['var time=' + ctime.__str__() + ';']
        
    # Build the content
    content = self.generate('chatblock.tpl.html')
    self.css = ['chatblock.css', 'chessarea.css']
    
    content += self.generate('chessarea.tpl.html', {'chessboard': utilities.get_chessboard_html()})
    
    self.response.out.write(self.generate_page({'content': content}))
  
      

class RoomListHandler(BaseRequestHandler):

  def get(self):
    # Get list of all current active games
    ltime = datetime.datetime.now() - datetime.timedelta(seconds = 60)
    
    rooms = Room.gql("WHERE active=:1 AND accessed>=:2", True, ltime)
    if rooms.count() == 0:
      rooms = None
    
    res = self.generate("roomlist.tpl.html", {'rooms': rooms})
    
    self.response.out.write(res)